﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Windows.Browser;
using System.Runtime.Serialization.Json;
using System.Xml;
using System.ServiceModel.Syndication;
using GoogleSearch.Model;
using System.Collections.ObjectModel;
using System.Windows.Data;

namespace GoogleSearch.Views
{
    public partial class Search : Page
    {
        const string GOOGLE_SEARCH_URL = "http://ajax.googleapis.com/ajax/services/search/web?v={0}&q={1}&rsz={2}&start={3}";
        const string GOOGLE_SERACH_API_VERSION = "1.0";
        string resultSize = "large";
        int PAGE_SIZE = 8;
        string lastPhrase = "";
        int startIndex = 0;
        ObservableCollection<GoogleSearchResult> results = new ObservableCollection<GoogleSearchResult>();
        PagedCollectionView pcv;

        public Search()
        {
            InitializeComponent();
            pcv = new PagedCollectionView(results);

            if (!Application.Current.IsRunningOutOfBrowser)
            {
                ColumnLeft.Width = new GridLength(ColumnLeft.Width.Value + ColumnRight.Width.Value);
                ColumnRight.Width = new GridLength(0);
            }

            Loaded += new RoutedEventHandler(Search_Loaded);    
			StoryboardInit.Begin();
        }

        void Search_Loaded(object sender, EventArgs e)
        {
            this.Results.ItemsSource = pcv;
            this.SearchTextBox.Focus();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void doSearch()
        {            
            if (!string.IsNullOrEmpty(SearchTextBox.Text))
            {
                //StoryboardAfterSearchPressed.Completed += new System.EventHandler(StoryboardAfterSearchPressed_Completed);
                StoryboardAfterSearchPressed.Begin();
				BusyIndicator.IsBusy = true;

                if (lastPhrase != SearchTextBox.Text)
                {
                    PrevPageBtn.IsEnabled = false;
                    startIndex = 0;
                    lastPhrase = SearchTextBox.Text;
                    NextPageBtn.Visibility = PrevPageBtn.Visibility = Visibility.Visible;
                }
                
                WebClient client = new WebClient();
                //client.Headers.Add("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
                client.OpenReadAsync(new Uri(string.Format(GOOGLE_SEARCH_URL, GOOGLE_SERACH_API_VERSION, HttpUtility.UrlEncode(SearchTextBox.Text), resultSize, startIndex)));
            }
            else
            {
                ErrorWindow errorWindow = new ErrorWindow("No phrase to search for!", "You have to enter a phrase to search for on Google.");
                errorWindow.Show();
            }
        }

        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                List<GoogleSearchResult> resultList = new List<GoogleSearchResult>();

                XmlReader reader = JsonReaderWriterFactory.CreateJsonReader(e.Result, XmlDictionaryReaderQuotas.Max);

                results.Clear();
                while (reader.Read())
                {
                    //string xml = reader.ReadOuterXml();
                    if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "cursor") break;
                    if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "item")
                    {                      
                        GoogleSearchResult resultItem = new GoogleSearchResult();
                        reader.ReadToDescendant("unescapedUrl");
                        resultItem.UnescapedUrl = reader.ReadElementContentAsString();
                        reader.MoveToContent();
                        resultItem.Url = reader.ReadElementContentAsString();
                        reader.MoveToContent();
                        resultItem.VisibleUrl = reader.ReadElementContentAsString();
                        reader.ReadToFollowing("titleNoFormatting");
                        reader.MoveToContent();
                        resultItem.TitleNoFormatting = reader.ReadElementContentAsString();
                        reader.MoveToContent();
                        resultItem.Content = reader.ReadElementContentAsString();

                        //resultList.Add(resultItem);
                        results.Add(resultItem);
                    }
                }
            }
            else
            {
                ErrorWindow errorWindow = new ErrorWindow(e.Error);
                errorWindow.Show();
            }
            BusyIndicator.IsBusy = false;
			//if (StoryboardAfterSearchPressed.GetCurrentState() == ClockState.Stopped) {
                StoryboardAfterSearchCompleted.Begin();	
			//}
        }

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            doSearch();
        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            if (Application.Current.IsRunningOutOfBrowser)
            {
                WebBrowserQuick.Visibility = System.Windows.Visibility.Visible;
                string url = ((HyperlinkButton)sender).CommandParameter.ToString();
                WebBrowserQuick.NavigateToString("<iframe src=\"" + url + "\" style=\"width: 100%; height: 100%; margin: 0; border: 0;\"></iframe>");
            }
            else
            {
                ChildWindow win = new ChildWindow();
                win.Title = "Information";
                win.Width = 250;
                StackPanel panel = new StackPanel();
                TextBlock txtBlock = new TextBlock();
                txtBlock.TextWrapping = TextWrapping.Wrap;
                txtBlock.Text = (Application.Current.InstallState == InstallState.Installed) ? "Application has to be installed and running out of browser in order to enable the Preview functionality." : "Application is installed, but it has to be running out of browser in order to enable the Preview functionality.";
                Button btn = new Button();
                btn.Content = "Close";
                btn.Click += delegate
                {
                    win.Close();
                };
                btn.Width = 80;
                panel.Children.Add(txtBlock);
                panel.Children.Add(btn);
                win.Content = panel;
                win.HasCloseButton = true;                
                win.Show();
            }
        }

        private void PrevPageBtn_Click(object sender, RoutedEventArgs e)
        {
            if (startIndex >= PAGE_SIZE)
            {
                startIndex -= PAGE_SIZE;
                SearchTextBox.Text = lastPhrase;
                if (startIndex == 0) PrevPageBtn.IsEnabled = false;

                doSearch();
            }
        }

        private void NextPageBtn_Click(object sender, RoutedEventArgs e)
        {
            startIndex += PAGE_SIZE;
            SearchTextBox.Text = lastPhrase;
            PrevPageBtn.IsEnabled = true;

            doSearch();
        }

        private void SearchTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                doSearch();
            }
        }

        //private void StoryboardAfterSearchPressed_Completed(object sender, System.EventArgs e)
        //{
        //    StoryboardAfterSearchCompleted.Begin();
        //}
    }
}
